<template>
  <div class="upload-body">
    <el-dialog
      v-model="centerDialogVisible"
      :title="payPopType == 0 ? '充电' : '付费内容'"
      width="500px"
      center
      @close="close"
    >
      <!-- 设置支付密码弹框 -->
      <el-dialog v-model="setPayPwdPopVisible" title="设置支付密码" width="500px" center>
        <span>您还没有设置支付密码,是否前往设置?</span>
        <template #footer>
          <div class="set-pwd-btn-box f-a-c">
            <div class="btn close-btn f-j-a-c" @click="setPayPwdPopVisible = false">
              取消
            </div>
            <el-button class="btn confirm-btn f-j-a-c" @click="toSetPwd">确定</el-button>
          </div>
        </template>
      </el-dialog>

      <payPwdPop
        ref="payPwdRef"
        @confirm="postPostsPay"
        :payInfo="payObjInfo"
      ></payPwdPop>

      <!-- 充电 -->
      <div v-if="payPopType == 0">
        <div class="user-info-header f-a-c" v-if="payInfo.user">
          <userAvatar :userImgs="payInfo.user.user_avatar"></userAvatar>
          <div class="user-name-info">
            <div class="user-name">{{ payInfo.user.user_name }}</div>
            <div class="user-title">谢谢你的支持和打赏~</div>
          </div>
        </div>

        <!-- (充电)价格列表 -->
        <div class="price-list">
          <div
            v-for="(item, index) in priceList"
            :key="index"
            @click="activeIndex = index"
          >
            <div
              v-if="item.type == 'number'"
              class="price-item-number f-j-a-c"
              :class="{
                'price-item-number-active': activeIndex == index,
              }"
            >
              ￥ {{ item.value }}
            </div>

            <el-input
              class="price-item-input"
              v-model="item.value"
              v-if="item.type == 'input'"
              placeholder="自定义"
              :class="{ 'price-item-input-active': activeIndex == index && item.value }"
              type="number"
            ></el-input>
          </div>
        </div>
      </div>

      <!-- 帖子付费内容信息 -->
      <div class="pay-info-box" v-if="payPopType == 1 && payInfo.pay_obj">
        <div
          class="pay-info-item f-a-c"
          v-for="(item, index) in payInfoList"
          :key="index"
        >
          <div class="pay-info-item-title">{{ item.title }}:</div>

          <div class="pay-info-item-num">
            <span>
              {{
                item.key == "words_percent"
                  ? 100 - payInfo.pay_obj[item.key]
                  : payInfo.pay_obj[item.key]
              }}
            </span>

            <!-- <span v-if="item.unit == '余额'">&nbsp;{{ payInfo.pay_obj.credit }}</span> -->
            <span>&nbsp;{{ item.unit }}</span>
          </div>
        </div>
      </div>

      <!-- 说明 -->
      <div class="pay-title">
        虚拟物品存在可复制性，请谨慎购买，不可退货，若不慎被骗，请立即举报并说明原因
      </div>

      <!-- 支付类型 -->
      <el-radio-group v-model="payType" class="pay-type f-j-sb-a-c">
        <el-radio label="0">余额支付（余额：￥{{ balance || 0 }}）</el-radio>
        <!-- <el-radio label="1">扫码支付</el-radio> -->
      </el-radio-group>

      <!-- 是否使用硬币抵扣 -->
      <el-radio
        v-if="payType === '0'"
        class="pay-type"
        v-model="isDeduction"
        :label="true"
        @click.native.prevent="deductionClick"
      >
        {{ coinsConfig.name }}抵扣
        <span class="deduction-num"
          >￥{{ goldCredit.price }} (消耗{{ goldCredit.gold }}{{ coinsConfig.name }})
        </span>
      </el-radio>

      <!-- 充电金额 -->
      <div class="recharge-num f-j-a-c" v-if="payPopType == 0">
        <span>充电金额:</span>
        <span class="num">￥{{ priceList[activeIndex].value || 0 }}</span>
      </div>

      <!-- 充电确定按钮 -->
      <div class="btn-box f-j-a-c" v-if="payType === '0' && payPopType == 0">
        <div class="confirm-btn f-j-a-c" @click="openPayPwdPop">确定</div>
      </div>

      <!-- 帖子付费立即购买按钮 -->
      <div class="btn-box f-j-a-c" v-if="payType === '0' && payPopType == 1">
        <div class="confirm-btn f-j-a-c" @click="openPayPwdPop">立即购买</div>
      </div>

      <!-- 二维码 -->
      <div class="f-j-a-c pay-qr-box" v-if="payType == '1'">
        <div class="f-d-c f-j-a-c">
          <vue-qr text="wwwww.baidu.com" :size="140" :margin="10"></vue-qr>
          <div class="qr-text f-a-c">
            <svg-icon class="svg" name="icon-wx"></svg-icon>
            微信支付
          </div>
        </div>
      </div>

      <!-- 余额不足 -->
      <div class="not-blance f-j-a-c" v-if="(balance || balance!=='') && balance < payBalance">
        <!-- 余额不足，请更换扫码支付或 <span>充值</span> -->
        余额不足, 请前往 <span @click="toAccountSetting">充值</span>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import vueQr from "vue-qr/src/packages/vue-qr.vue";
import userAvatar from "@/components/userAvatar.vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { postsPay, balancePay, myFinancialSetUserid } from "@/axios/community.js";
import { toFixedNum } from "@/utils/common.js";
import { showLoading, hideLoading } from "@/utils/loading.js";
import payPwdPop from "./payPwdPop.vue";
import {
  defineComponent,
  reactive,
  toRefs,
  onUnmounted,
  onMounted,
  computed,
  watch,
  getCurrentInstance,
  ref,
} from "vue";
export default defineComponent({
  props: {
    payPopType: {
      type: [Number, String],
      default: 0,
    }, //弹框类型  0 充电 1付费
    payInfo: {
      type: Object,
      default: () => {},
    }, //支付信息
    postIndex: {
      type: [Number, String],
      default: 0,
    }, //帖子下标
  },
  components: {
    userAvatar,
    vueQr,
    payPwdPop,
  },
  setup(props, { attrs, slots, emit }) {
    const router = useRouter();
    const { proxy } = getCurrentInstance();
    const store = useStore();

    const payPwdRef = ref(null);

    let data = reactive({
      setPayPwdPopVisible: false,
      centerDialogVisible: false,
      priceList: [
        {
          value: "2",
          type: "number",
          id: 1,
        },
        {
          value: "5",
          type: "number",
          id: 2,
        },
        {
          value: "10",
          type: "number",
          id: 3,
        },

        {
          value: "50",
          type: "number",
          id: 4,
        },
        {
          value: "100",
          type: "number",
          id: 5,
        },
        {
          value: "",
          type: "input",
          id: 6,
        },
      ],
      activeIndex: 0, //选中id
      payType: "0", //支付类型
      isDeduction: false, //是否使用硬币抵扣
      payInfoList: [
        {
          title: "价格",
          key: "price",
          unit: "余额",
        },
        {
          title: "剩余篇幅",
          key: "words_percent",
          unit: "%",
        },
        {
          title: "隐藏内容",
          key: "has_hidden",
          unit: "字符",
        },
        {
          title: "附件数量",
          key: "has_file",
          unit: "",
        },
      ],
      coins: "", //硬币
      balance: "", //余额
    });

    // 获取用户余额
    let getMyFinancialSetUserid = () => {
      myFinancialSetUserid({
        id: 0,
      }).then((res) => {
        data.coins = res.data.coins.total; //硬币
        data.balance =res.data.financial?res.data.financial.balance:0; //余额
      });
    };

    // 金币配置
    let coinsConfig = computed(() => {
      let setting = store.state.globalConfig;
      return setting.app.coins;
    });

    // 需要支付的金额
    let payBalance = computed(() => {
      let payPrice =
        props.payPopType == 1
          ? props.payInfo.pay_obj.price
          : data.priceList[data.activeIndex].value;
      return payPrice - (data.isDeduction ? goldCredit.value.price : 0);
    });

    // 硬币抵扣(后续还需判断用户余额)
    let goldCredit = computed(() => {
      let payPrice =
        props.payPopType == 1
          ? props.payInfo.pay_obj.price
          : data.priceList[data.activeIndex].value;

      let maxCredit = payPrice * (coinsConfig.value.percent_every / 100); //最大抵扣金额
      let maxGold = maxCredit * coinsConfig.value.rate; //最大抵扣金额所需硬币
      //如果用户硬币不足
      // maxCredit
      if (maxGold > data.coins) {
        return {
          price: data.coins / coinsConfig.value.rate,
          gold: data.coins, //用户所有硬币
        };
      } else {
        return {
          price: maxCredit,
          gold: maxGold,
        };
      }
    });

    // 弹框支付信息(后续还需判断用户余额)
    let payObjInfo = computed(() => {
      let payPrice =
        props.payPopType == 1
          ? props.payInfo.pay_obj.price
          : data.priceList[data.activeIndex].value;
      return {
        isDeduction: data.isDeduction, //是否使用硬币抵扣
        price: payPrice - (data.isDeduction ? goldCredit.value.price : 0), //需支付余额
        maxGold: goldCredit.value.gold, //消耗多少硬币
        maxCredit: goldCredit.value.price, //抵扣多少金额
        goldName: coinsConfig.value.name,
        payTitle: data.payType == 1 ? "购买付费" : "充电",
      };
    });

    // 打开弹框
    let open = () => {
      getMyFinancialSetUserid();
      data.centerDialogVisible = true;
      emit("open");
    };

    // 取消
    let close = () => {
      data.centerDialogVisible = false;
      emit("close");
    };

    // 前往设置支付密码
    let toSetPwd = () => {
      data.setPayPwdPopVisible = false;
      router.push({
        path: "/accoutSetting",
        query: {
          pwd: true,
        },
      });
    };

    // 打开输入密码弹框
    let openPayPwdPop = () => {
      if (!store.state.minUserInfo.paycode) {
        data.setPayPwdPopVisible = true;
        return;
      }

      if (data.balance < payBalance.value) {
        return ElMessage.warning("余额不足");
      }
      payPwdRef.value.open();
    };

    // 是否使用硬币抵扣点击
    let deductionClick = () => {
      data.isDeduction = !data.isDeduction;
    };

    // 购买帖子
    let postPostsPay = (pwd) => {
      showLoading();
      let params;
      // 充电
      if (props.payPopType == 0) {
        params = {
          order: {
            postsId: props.payInfo.id, //帖子id
            coins_num: data.isDeduction ? goldCredit.value.gold : 0, //抵扣硬币数量
            postsUserId: props.payInfo.user_id, //打赏用户id
            rewardPrice: data.priceList[data.activeIndex].value, //打赏金额
            type: 2,
          },
          // paycode: ["1", "2", "3", "4", "5", "6"], //支付密码
          paycode: (pwd + "").split(""), //支付密码
        };
      } else if (props.payPopType == 1) {
        // 购买帖子
        params = {
          order: {
            post_id: props.payInfo.id, //帖子id
            postIndex: props.postIndex, //帖子下标
            coins_num: data.isDeduction ? goldCredit.value.gold : 0, //抵扣硬币数量
            scene: 10,
            type: 4,
          },
          // paycode: ["1", "2", "3", "4", "5", "6"], //支付密码
          paycode: (pwd + "").split(""), //支付密码
        };
      }

      // 余额支付 / 组合支付
      balancePay(params)
        .then((res) => {
          hideLoading();
          ElMessage.success(props.payPopType == 0 ? res.data.tip : "支付成功!");
          // 购买帖子成功后 更新帖子内容
          if (props.payPopType == 1) {
            emit("paySuccess", res.data[0]);
          }
          close();
        })
        .catch((err) => {
          hideLoading();
        });
    };

    // 前往充值
    let toAccountSetting = () => {
      router.push({
        path: "/accoutSetting",
        query: {
          TopUpNowType: true,
        },
      });
    };

    return {
      toSetPwd,
      toAccountSetting,
      payBalance,
      payObjInfo,
      openPayPwdPop,
      payPwdRef,
      goldCredit,
      coinsConfig,
      postPostsPay,
      deductionClick,
      close,
      confirm,
      open,
      ...toRefs(data),
    };
  },
});
</script>
<style lang="scss" scoped>
.upload-body {
  :deep(.el-dialog.el-dialog--center) {
    border-radius: 20px;
    // width: 400px;
    // width: 500px;
  }

  :deep(.el-dialog--center .el-dialog__footer) {
    text-align: right !important;
  }
}

.user-info-header {
  .user-name-info {
    padding-left: 10px;
    .user-name {
      font-size: 14px;
      font-weight: bold;
      color: #000000;
    }
    .user-title {
      font-size: 12px;
      line-height: 13px;
      color: #656f79;
      padding-top: 6px;
    }
  }
}

// 价格列表
.price-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, 30%);
  grid-gap: 20px 5%;
  padding-top: 20px;

  .price-item-number {
    cursor: pointer;
    height: 40px;
    border-radius: 10px;
    background: #f3f4f5;
    font-size: 16px;
    color: #656f79;
    font-weight: bold;
  }
  .price-item-number-active {
    background: rgba(100, 200, 220, 0.1);
    border: 1px solid #64c8dc;
    color: #64c8dc;
  }

  .price-item-input {
    text-align: center;
    :deep(.el-input__wrapper) {
      border-radius: 10px;
      background: #f3f4f5;
      height: 40px;
      box-shadow: none;
      text-align: center;
    }
    :deep(.el-input__inner) {
      text-align: center;
      font-size: 16px;
      font-weight: bold;
      color: #64c8dc;
    }
    :deep(.el-input__wrapper.is-focus) {
      border: 1px solid #64c8dc;
      background: rgba(100, 200, 220, 0.1);
    }
  }

  .price-item-input-active {
    :deep(.el-input__wrapper) {
      border: 1px solid #64c8dc;
      background: rgba(100, 200, 220, 0.1);
    }
  }
}

// 付费内容信息
.pay-info-box {
  .pay-info-item {
    height: 40px;
    border-radius: 10px;
    background: #f3f4f5;
    margin-bottom: 10px;
    font-size: 14px;

    .pay-info-item-title {
      width: 110px;
      padding: 0 20px;
      color: #000000;
    }
    .pay-info-item-num {
      color: #656f79;
    }
  }
  > div:last-child {
    margin-bottom: 0;
  }
}

// 说明
.pay-title {
  font-size: 12px;
  color: #656f79;
  padding-top: 10px;
  line-height: 20px;
}

// 支付类型
.pay-type {
  // padding-right: 20px;
  padding-top: 20px;
  :deep(.el-radio__input.is-checked .el-radio__inner) {
    background: #64c8dc;
    background-color: #64c8dc;
    border-color: #64c8dc;
  }
  :deep(.el-radio__label) {
    font-size: 14px;
    color: #000000;
  }
  :deep(.el-radio__input.is-checked + .el-radio__label) {
    // color: #64c8dc;
  }
  .deduction-num {
    color: #ff425b;
  }
}

// 金额
.recharge-num {
  font-size: 16px;
  color: #000000;
  padding-top: 30px;
  > .num {
    color: #ff425b;
    padding-left: 5px;
  }
}

// 二维码
.pay-qr-box {
  padding-top: 10px;

  .qr-text {
    font-size: 14px;
    color: #000000;
    .svg {
      width: 20px;
      height: 20px;
      margin-right: 10px;
    }
  }
}

// 立即购买按钮
.btn-box {
  font-size: 14px;
  font-weight: bold;
  padding-top: 30px;
  > div {
    height: 36px;
    width: 180px;
    border-radius: 40px;
    cursor: pointer;
    background: linear-gradient(90deg, #9ed8e6 0%, #a1f0c0 100%);
    color: #ffffff;
    &:active {
      opacity: 0.7;
    }
  }
}

// 余额不足
.not-blance {
  font-size: 12px;
  color: #ff425b;
  padding-top: 20px;
  > span {
    cursor: pointer;
    color: #64c8dc;
  }
}

// 设置密码提示弹框
.set-pwd-btn-box {
  font-size: 14px;
  font-weight: bold;
  justify-content: flex-end;
  > .btn {
    height: 36px;
    width: 80px;
    border-radius: 10px;
    margin-left: 10px;
    cursor: pointer;
    background: #f3f4f5;
    color: #656f79;
    &:active {
      opacity: 0.7;
    }
  }
  .confirm-btn {
    background: linear-gradient(90deg, #9ed8e6 0%, #a1f0c0 100%);
    color: #ffffff;
    border: none;
  }
}
</style>
